package com.zhouyibike.uu.ui.activity.mybike.Twentyoffer;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Handler;
import android.os.Message;
import android.os.Bundle;
import android.text.TextPaint;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.squareup.picasso.Callback;
import com.squareup.picasso.NetworkPolicy;
import com.squareup.picasso.Picasso;
import com.tencent.mm.opensdk.constants.Build;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.zhouyibike.uu.R;
import com.zhouyibike.uu.config.Config;
import com.zhouyibike.uu.entity.PayResult;
import com.zhouyibike.uu.entity.TwentyActivityResult;
import com.zhouyibike.uu.entity.TwentyBuyResult;
import com.zhouyibike.uu.http.ApiCallback;
import com.zhouyibike.uu.ui.base.BaseActivity;
import com.zhouyibike.uu.utils.DataSingle;
import com.zhouyibike.uu.utils.Util;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;

public class PayActivity20 extends BaseActivity implements View.OnClickListener {
    private TextView mBtnTitle;
    private Button buy20bt, closedialog, btn_buy_sure;
    private ImageButton mBtnBack;
    private LinearLayout zfbly, wxly;
    private Dialog buydialog;
    private CheckBox wxcb, zfbcb;
    private int paytype = 1;//1支付宝2微信
    private IWXAPI api;
    private ImageView buy20bg,titleiv;
    private List<TwentyActivityResult.DataBean.ImagesBean> imagesBeen = new ArrayList<>();
    private int shengche=0;
    private RelativeLayout rly,huodongjiazai;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pay20);
        api = WXAPIFactory.createWXAPI(this, null);
        EventBus.getDefault().register(this);
        initView();
        huodongjiazai= (RelativeLayout) findViewById(R.id.huodongjiazai);
        imagesBeen = (List<TwentyActivityResult.DataBean.ImagesBean>) getIntent().getSerializableExtra("chong20");
        shengche=getIntent().getIntExtra("shengche20",0);
        rly= (RelativeLayout) findViewById(R.id.rly);
        TextView tv=new TextView(this);
        rly.addView(tv);
        RelativeLayout.LayoutParams lp= (RelativeLayout.LayoutParams) tv.getLayoutParams();
        lp.height= (int)((DataSingle.getInstance().PhoneH-DataSingle.getInstance().StatusBarH-Util.dp2px(this,48))*0.06);
        lp.width= (int) (DataSingle.getInstance().PhoneW*0.185);
        lp.setMargins((int)(DataSingle.getInstance().PhoneW*0.35),(int)((DataSingle.getInstance().PhoneH-DataSingle.getInstance().StatusBarH-Util.dp2px(this,48))*0.32),0,0);
        tv.setLayoutParams(lp);
        tv.setText(""+shengche);
        tv.setTextColor(Color.rgb(1,205,255));//#01CDFF1,205,255
//        tv.setBackgroundColor(Color.rgb(1,205,255));//#01CDFF1,205,255
        tv.setTextSize(26);
      //  tv.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG); //UNDERLINE_TEXT_FLAG下划线删除线STRIKE_THRU_TEXT_FLAG
      //  tv.getPaint().setAntiAlias(true);//抗锯齿
        tv.setGravity(Gravity.CENTER);
        TextPaint tp = tv.getPaint();  tp.setFakeBoldText(true);
        tv.setTypeface(Typeface.DEFAULT_BOLD, Typeface.BOLD);//Typeface.MONOSPACE, Typeface.BOLD_ITALIC
        initDailog(paytype);
        initListener();
        setimage();
    }

    private void setimage() {
        try {
            if (imagesBeen != null && imagesBeen.size() > 0) {
    //            RelativeLayout.LayoutParams linearParams = (RelativeLayout.LayoutParams) mBtnTitle.getLayoutParams(); //取控件textView当前的布局参数
    //            linearParams.height = Util.dp2px(this, 24);// 控件的高强制设成20
    //            linearParams.width = Util.dp2px(this, 110);// 控件的宽强制设成30
    //            mBtnTitle.setLayoutParams(linearParams); //使设置好的布局参数应用到控件</pre>
                //  mBtnTitle.setBackground(getResources().getDrawable(R.drawable.chong20qiangdanchetitle));
                Picasso.with(mActivity).load(imagesBeen.get(1).getImagePath()) .networkPolicy(NetworkPolicy.NO_CACHE,NetworkPolicy.NO_STORE).into(titleiv);
                titleiv.setVisibility(View.VISIBLE);
                Picasso.with(mActivity).load(imagesBeen.get(2).getImagePath()) .networkPolicy(NetworkPolicy.NO_CACHE,NetworkPolicy.NO_STORE).into(buy20bg, new Callback() {
                    @Override
                    public void onSuccess() {
                        huodongjiazai.setVisibility(View.GONE);
                        rly.setVisibility(View.VISIBLE);
                    }

                    @Override
                    public void onError() {

                    }
                });
                Util.setRtitle(titleiv,Double.parseDouble(imagesBeen.get(1).getWidth()),Double.parseDouble(imagesBeen.get(1).getHeight()),Util.dp2px(this,22));
            }
        } catch (Exception e) {
//            toastShow("未获取到活动信息");
        }
    }
    private void initView() {
        mBtnBack = (ImageButton) findViewById(R.id.bar_btn_back);
        mBtnTitle = (TextView) findViewById(R.id.bar_text_title);
//        RelativeLayout.LayoutParams linearParams = (RelativeLayout.LayoutParams) mBtnTitle.getLayoutParams(); //取控件textView当前的布局参数
//        linearParams.height = Util.dp2px(this, 24);// 控件的高强制设成20
//        linearParams.width = Util.dp2px(this, 110);// 控件的宽强制设成30
//        mBtnTitle.setLayoutParams(linearParams); //使设置好的布局参数应用到控件</pre>
//        mBtnTitle.setBackground(getResources().getDrawable(R.drawable.chong20qiangdanchetitle));
//        mBtnTitle.setText("充20抢单车");
        buy20bt = (Button) findViewById(R.id.buy20bt);
        buy20bg = (ImageView) findViewById(R.id.buy20bg);
        titleiv= (ImageView) findViewById(R.id.titleiv);
    }

    private void initListener() {
        buy20bt.setOnClickListener(this);
        mBtnBack.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.buy20bt:
                buydialog.show();
                break;
            case R.id.bar_btn_back:
                finish();
                break;
        }
    }

    /**
     * 信息显示dialog
     */
    private void initDailog(int type) {
        View view = LayoutInflater.from(this).inflate(
                R.layout.buy20_dialog, null);
        buydialog = new Dialog(this, R.style.Dialog_Fullscreen);
        zfbly = view.findViewById(R.id.zfbly);
        wxly = view.findViewById(R.id.wxly);
        wxcb = view.findViewById(R.id.cb_buy20_wx);
        zfbcb = view.findViewById(R.id.cb_buy20_zfb);
        btn_buy_sure = view.findViewById(R.id.btn_buy_sure);
        closedialog = view.findViewById(R.id.pay20_colse_dialog);
        closedialog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                buydialog.dismiss();
            }
        });
//        wxly.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                paytype=2;
//                if (paytype==2)
//                {
//                    wxcb.setChecked(true);
//                    zfbcb.setChecked(false);
//                }else{
//                    wxcb.setChecked(false);
//                    zfbcb.setChecked(true);
//                }
//            }
//        });
//        zfbly.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                paytype=1;
//                if (paytype==2)
//                {
//                    wxcb.setChecked(true);
//                    zfbcb.setChecked(false);
//                }else{
//                    wxcb.setChecked(false);
//                    zfbcb.setChecked(true);
//                }
//            }
//        });
        wxcb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                paytype = 2;
                if (paytype == 2) {
                    wxcb.setChecked(true);
                    zfbcb.setChecked(false);
                } else {
                    wxcb.setChecked(false);
                    zfbcb.setChecked(true);
                }
            }
        });
        zfbcb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                paytype = 1;
                if (paytype == 2) {
                    wxcb.setChecked(true);
                    zfbcb.setChecked(false);
                } else {
                    wxcb.setChecked(false);
                    zfbcb.setChecked(true);
                }
            }
        });
        btn_buy_sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                buymsg();
            }
        });
        buydialog.setContentView(view, new LinearLayout.LayoutParams(
                (int) (DataSingle.getInstance().PhoneW * 0.8),
                LinearLayout.LayoutParams.WRAP_CONTENT));
        buydialog.getWindow().setWindowAnimations(R.style.mypopwindow_anim_style3);  //添加动画
        buydialog.setCancelable(true);
        buydialog.setCanceledOnTouchOutside(true);
        buydialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
    }

    private void buymsg() {
        Map<String, String> params = new HashMap<>();
        params.put("token", preferences.getString("token", ""));
        showProgressDialog();
        addSubscription(apiStores.TwentyBuy(params),
                new ApiCallback<TwentyBuyResult>() {

                    @Override
                    public void onSuccess(TwentyBuyResult model) {
                        if (model.getStatus() == Config.SUCCESSCODE) {
//                            paysuccess();
                            if (paytype == 1) {
                                zfbpay(model.getData().getAlipay());
                            } else {
                                wxpay(model.getData().getWeChatPay());
                            }
                        } else {
                            toastShow(model.getMessage());
                        }
                    }

                    @Override
                    public void onFailure(String msg) {
                        toastShow(msg);

                    }

                    @Override
                    public void onFinish() {
                        dismissProgressDialog();
                    }
                });
    }

    private void paysuccess() {
        setResult(20);//回传给main刷新
        Intent i=new Intent(this, Buy20SuccessActivity.class);
        i.putExtra("shengche20",shengche);
        i.putExtra("chong20", (Serializable) imagesBeen);
        startActivity(i);
        finish();
//        toastShow("支付成功");
    }

    private void wxpay(TwentyBuyResult.DataBean.WeChatPayBean model) {
        TwentyBuyResult.DataBean.WeChatPayBean model1 = model;
        api.registerApp(model.getAppId());
        boolean isPaySupported = api.getWXAppSupportAPI() >= Build.PAY_SUPPORTED_SDK_INT;
        if (!isPaySupported) {
            Toast.makeText(PayActivity20.this, "您的微信版本太低，不支持支付功能", Toast.LENGTH_SHORT).show();
            return;
        }
        Toast.makeText(PayActivity20.this, "获取订单中...", Toast.LENGTH_SHORT).show();
        try {
            PayReq request = new PayReq();

            request.appId = model.getAppId();

            request.partnerId = model.getPartnerId();

            request.prepayId = model.getPrepayId();

            request.packageValue = "Sign=WXPay";

            request.nonceStr = model.getNoncestr();

            request.timeStamp = model.getTimestamp();

            request.sign = model.getSign();

            api.sendReq(request);

        } catch (Exception e) {
            Toast.makeText(PayActivity20.this, "异常：" + e.getMessage(), Toast.LENGTH_SHORT).show();
        }

    }

    @Subscribe(threadMode = ThreadMode.MainThread)
    public void wxpayresult(Integer progress) {
        if (progress == 0) {//支付成功
            paysuccess();
        } else {
            Toast.makeText(PayActivity20.this, "支付失败", Toast.LENGTH_SHORT).show();
        }
    }

    private void zfbpay(final String orderinfo) {

        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(PayActivity20.this);
                Map<String, String> result = alipay.payV2(orderinfo, true);
                Log.i("msp", result.toString());

                Message msg = new Message();
                msg.what = 1;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (resultStatus.equals("9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        paysuccess();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        Toast.makeText(PayActivity20.this, "支付失败", Toast.LENGTH_SHORT).show();
                    }
                    break;
                }
                default:
                    break;
            }
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
